﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Configuration;

namespace _05_配置提供者_02
{
    class FxConfigProvider : FileConfigurationProvider
    {
        public FxConfigProvider(FxConfigSource src) : base(src)
        { 
        }

        public override void Load(Stream stream)
        {
            // 忽略大小写
            var data = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(stream);
            var nodes = xmlDoc.SelectNodes("/configuration/connectionStrings/add");
            foreach (XmlNode node in nodes.Cast<XmlNode>())
            {
                var name = node.Attributes["name"].Value;
                var connectionString = node.Attributes["connectionString"].Value;
                data[$"{name}:connectionString"] = connectionString;

                var providerName = node.Attributes["providerName"].Value;
                if (providerName != null)
                {
                    data[$"{name}:providerName"] = providerName;
                }
            }
            var settingNodes = xmlDoc.SelectNodes("/configuration/appSettings/add");
            foreach(XmlNode node in settingNodes.Cast<XmlNode>())
            {
                var key = node.Attributes["key"].Value;
                string value= node.Attributes["value"].Value;
                data[key] = value;
            }
        }
    }
}
